package com.dongqi.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.Iterator;
import java.util.Set;

public class XmlUtils {
    /**
     * json转xml<br>
     * 方 法 名：jsonToXml <br>
     * @param json
     * @return String
     */
    public static String jsonToXml(String json){
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            buffer.append("<Data>");
            JSONObject jObj = JSON.parseObject(json);
            jsonToXmlstr(jObj,buffer);
            buffer.append("</Data>");
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * json转str<br>
     * 方 法 名：jsonToXmlstr <br>
     * @param jObj
     * @param buffer
     * @return String
     */
    public static String jsonToXmlstr(JSONObject jObj, StringBuffer buffer ){
        Set<Entry<String, Object>> se = jObj.entrySet();
        for(Iterator<Entry<String, Object>> it = se.iterator(); it.hasNext(); )
        {
            Entry<String, Object> en = it.next();
            if(en.getValue() != null && en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONObject")){
                buffer.append("<"+en.getKey()+">");
                JSONObject jo = jObj.getJSONObject(en.getKey());
                jsonToXmlstr(jo,buffer);
                buffer.append("</"+en.getKey()+">");
            }else if(en.getValue() != null && en.getValue().getClass().getName().equals("com.alibaba.fastjson.JSONArray")){
                if (en.getKey().equals("extproperties")) {
                    JSONArray ja = jObj.getJSONArray(en.getKey());
                    Iterator<Object> it1 = ja.iterator();
                    List<String> list=new ArrayList<String>();
                    while (it1.hasNext()) {
                        String ob = (String) it1.next();
                        System.out.println(ob);
                    }
                }else {
                    JSONArray jarray = jObj.getJSONArray(en.getKey());
                    for (int i = 0; i < jarray.size(); i++) {
                        buffer.append("<"+en.getKey()+">");
                        JSONObject jsonobject =  jarray.getJSONObject(i);
                        jsonToXmlstr(jsonobject,buffer);
                        buffer.append("</"+en.getKey()+">");
                    }
                }

            }else if(en.getValue() != null && en.getValue().getClass().getName().equals("java.lang.String")){
                buffer.append("<"+en.getKey()+">"+en.getValue());
                buffer.append("</"+en.getKey()+">");
            }else{
                buffer.append("<"+en.getKey()+">"+"");
                buffer.append("</"+en.getKey()+">");
            }

        }
        return buffer.toString();
    }

    /**
     * xml转json字符串 注意:路径和字符串二传一另外一个传null<br>
     * 方 法 名：xmlToJson <br>
     * @param xmlPath xml路径(和字符串二传一,两样都传优先使用路径)
     * @param xmlStr xml字符串(和路径二传一,两样都传优先使用路径)
     * @return String
     * @throws IOException
     * @throws JDOMException
     */
    @SuppressWarnings("unchecked")
    public static String xmlToJson(String xmlPath,String xmlStr){
        SAXBuilder sbder = new SAXBuilder();
        Map<String, Object> map = new HashMap<String, Object>();
        Document document;
        try {
            if(xmlPath!=null){
                //路径
                document = sbder.build(new File(xmlPath));
            }else if(xmlStr!=null){
                //xml字符
                StringReader reader = new StringReader(xmlStr);
                InputSource ins = new InputSource(reader);
                document = sbder.build(ins);
            }else{
                return "{}";
            }
            //获取根节点
            Element el =  document.getRootElement();
            List<Element> eList =  el.getChildren();
            Map<String, Object> rootMap = new HashMap<String, Object>();
            //得到递归组装的map
            rootMap = xmlToMap(eList,rootMap);
            map.put(el.getName(), rootMap);
            //将map转换为json 返回
            return JSON.toJSONString(map);
        } catch (Exception e) {
            return "{}";
        }
    }

    /**
     * 节点转map<br>
     * 方 法 名：xmlToMap <br>
     * @param eList
     * @param map
     * @return Map<String,Object>
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> xmlToMap(List<Element> eList,Map<String, Object> map){
        for (Element e : eList) {
            Map<String, Object> eMap = new HashMap<String, Object>();
            List<Element> elementList = e.getChildren();
            if(elementList!=null&&elementList.size()>0){
                eMap = xmlToMap(elementList,eMap);
                Object obj = map.get(e.getName());
                if(obj!=null){
                    List<Object> olist = new ArrayList<Object>();
                    if(obj.getClass().getName().equals("java.util.HashMap")){
                        olist.add(obj);
                        olist.add(eMap);

                    }else if(obj.getClass().getName().equals("java.util.ArrayList")){
                        olist = (List<Object>)obj;
                        olist.add(eMap);
                    }
                    map.put(e.getName(), olist);
                }else{
                    map.put(e.getName(), eMap);
                }
            }else{
                map.put(e.getName(), e.getValue());
            }
        }
        return map;
    }

    /**
     * 将已经格式化的xml字符串写入xml文件
     * @param xmlStr
     * @return
     */
    public static boolean createXMLFile(String xmlStr,String xmlName){
        boolean flag = false;
        try {
            XMLWriter output = null;
            //OutputFormat   format   =   OutputFormat.createPrettyPrint();
            //format.setSuppressDeclaration(true);
            // format.setEncoding("UTF-8");

            //如果上面设置的xml编码类型为GBK，则应当用FileWriter来构建xml文件，否则会出现中文连码问题
                /*outpt = new XMLWriter(
                        new FileWriter(
                                new File("D:/myeclipse/Workspaces/fusionChartsDemoTest/WebRoot/xml/"+xmlName+".xml")) ,
                                    format);
                  */

            //如果上面设置的xml编码类型为utf-8，则应当用FileOutputStream来构建xml文件，否则还是会出现问题
            output = new XMLWriter(
                    new FileOutputStream(
                            new File("D:/Download/"+xmlName+".xml")));
            output.setEscapeText(false);
            output.write( xmlStr );
            output.close();
            return flag = true;

        } catch (IOException e) {
            e.printStackTrace();
            return flag;
        }

    }

    /**
     * 格式化xml
     * @param str
     * @return
     * @throws Exception
     */
    public static  String formatXML(String str) throws Exception {

        SAXReader reader=new SAXReader();

        //创建一个串的字符输入流
        StringReader in=new StringReader(str);
        org.dom4j.Document doc=reader.read(in);
        // 创建输出格式
        OutputFormat formater=OutputFormat.createPrettyPrint();
        //去掉xml文件的版本信息
        //formater.setSuppressDeclaration(true);
        //设置xml的输出编码
        formater.setEncoding("UTF-8");
        //创建输出(目标)
        StringWriter out=new StringWriter();
        //创建输出流
        XMLWriter writer=new XMLWriter(out,formater);
        //输出格式化的串到目标中，执行后。格式化后的串保存在out中。
        writer.write(doc);

        writer.close();

        // System.out.println(out.toString());

        //返回我们格式化后的结果
        return out.toString();
    }

}
